package com.huika.renrench.control.login.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.huika.lib.validation.EditTextValidator;
import com.huika.lib.validation.ValidationModel;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.Constant;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.login.validations.PassWordValidation;
import com.huika.renrench.control.login.validations.PhoneNumberValidation;
import com.huika.renrench.control.login.validations.VerifyNumberValidation;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.utils.LoginUtils;
import com.huika.renrench.utils.WebNetUtils;
import com.huika.renrench.view.TitleBarHelper;
import com.huika.renrench.view.clearedit.ClearableEditText;
import com.huika.renrench.view.webview.BaseWebViewAct;

public class RegisterActivity extends BaseAct {
	private ClearableEditText etPhone;
	private ClearableEditText etVerfy;
	private ClearableEditText etPwd;
	private TextView btnVerfy;
	private Button btnRegister;
	private CheckBox cbAgree;
	private TextView tvAgree;

	private EditTextValidator phoneValidator;
	private EditTextValidator editTextValidator;

	private String phone;
	private String pwd;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_register);
	}

	@Override
	protected void initWidget() {
		TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1, -1, R.string.title_register);
		titleBarHelper.setLeftMsg(R.string.left_back);
		etPhone = (ClearableEditText) findViewById(R.id.et_phone_ar);
		etVerfy = (ClearableEditText) findViewById(R.id.et_verfy_ar);
		etPwd = (ClearableEditText) findViewById(R.id.et_pwd_ar);
		btnVerfy = (TextView) findViewById(R.id.btn_verfy_ar);
		btnRegister = (Button) findViewById(R.id.btn_regist_ar);
		cbAgree = (CheckBox) findViewById(R.id.cb_agree_ar);
		tvAgree = (TextView) findViewById(R.id.tv_agree_ar);
		setVerfyEt(false);
		phoneValidator = new EditTextValidator(this).add(new ValidationModel(etPhone, new PhoneNumberValidation())).execute();
		editTextValidator = new EditTextValidator(this).add(new ValidationModel(etVerfy, new VerifyNumberValidation())).add(new ValidationModel(etPwd, new PassWordValidation()))
				.execute();
		etPhone.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() > 0) {
					if (!s.toString().substring(0, 1).equals("1")) {
						etPhone.setText("");
					} else if (s.length() > 1 && !s.toString().substring(1, 2).matches("[345789]")) {
						etPhone.setText("1");
						etPhone.setSelection(etPhone.length());
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		etPwd.addTextChangedListener(new MyPassWordWatcher(etPwd));
		initListener();
	}

	private void initListener() {
		btnRegister.setOnClickListener(this);
		btnVerfy.setOnClickListener(this);
		tvAgree.setOnClickListener(this);
	}

	class MyPassWordWatcher implements TextWatcher {
		private EditText editText;
		private String tempStr;

		public MyPassWordWatcher(EditText editText) {
			this.editText = editText;
		}

		@Override
		public void afterTextChanged(Editable s) {
			if (tempStr.indexOf(" ") != -1) {
				editText.setText(tempStr.trim());
				editText.setSelection(tempStr.length());
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (s.toString().equals(" ")) {
				editText.setText("");
			} else {
				tempStr = s.toString();
			}
		}

	}

	@Override
	public void widgetClick(View v) {
		switch (v.getId()) {
		case R.id.btn_verfy_ar:
			verfyNet();
			break;
		case R.id.btn_regist_ar:
			register();
			break;
		case R.id.tv_agree_ar:
			serviceAgree();
			break;

		default:
			break;
		}
	}

	private void serviceAgree() {
		Intent intent = new Intent(RegisterActivity.this, BaseWebViewAct.class);
		intent.putExtra(BaseWebViewAct.PAGE_URL, WebNetUtils.getWebUrl("8"));
		intent.putExtra(BaseWebViewAct.PAGE_TITLE, "人人创服务协议");
		intent.putExtra("left", "返回");
		intent.putExtra(BaseWebViewAct.IS_SHOW_BOTTOM, false);
		intent.putExtra(BaseWebViewAct.IS_HELP_FEEDBACK, true);
		showActivity(this, intent);
	}

	private void verfyNet() {
		if (phoneValidator.validate()) {
			showLoadingDialog("");
			phone = getInputStr(etPhone);
			FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.GETSMSVERIFICATION, codeListener, this, new TypeToken<RequestResult<String>>() {
			}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
			ajaxParams.putStringTypeParam("phone", phone);
			ajaxParams.putStringTypeParam("ip", GlobalApp.ip);
			ajaxParams.putStringTypeParam("mac", GlobalApp.mac);
			ajaxParams.putStringTypeParam("dev", Constant.DEV);
			request.setRequestParams(ajaxParams);
			executeRequest(request);
		}
	}

	private void register() {
		if (phoneValidator.validate() && editTextValidator.validate()) {
			if (!cbAgree.isChecked()) {
				showToastMsg("请同意人人创服务协议");
				return;
			}
			showLoadingDialog("");
			pwd = getInputStr(etPwd);
			FormResultRequest<UserModel> request = new FormResultRequest<UserModel>(UrlConstants.REGISTER, registerListener, this, new TypeToken<RequestResult<UserModel>>() {
			}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
			ajaxParams.putStringTypeParam("phone", phone);
			ajaxParams.putStringTypeParam("password", MD5Security.getMd5_32_UP(pwd));
			ajaxParams.putStringTypeParam("validateCode", getInputStr(etVerfy));
			ajaxParams.putStringTypeParam("ip", GlobalApp.ip);
			ajaxParams.putStringTypeParam("mac", GlobalApp.mac);
			ajaxParams.putStringTypeParam("dev", Constant.DEV);
			request.setRequestParams(ajaxParams);
			executeRequest(request);
		}
	}

	private Listener<RequestResult<String>> codeListener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			dismissLoadingDialog();
			showToastMsg(arg0.msg);
			btnVerfy.setClickable(false);
			setVerfyEt(true);
			new CountDownTimer(120000, 1000) {
				public void onTick(long millisUntilFinished) {
					btnVerfy.setTextColor(getResources().getColor(R.color.color_969696));
					btnVerfy.setText(String.format("%s秒", String.valueOf(millisUntilFinished / 1000)));
				}

				public void onFinish() {
					btnVerfy.setTextColor(getResources().getColor(R.color.color_f25522));
					btnVerfy.setText("免费获取验证码");
					btnVerfy.setClickable(true);
				}
			}.start();
		}
	};

	private Listener<RequestResult<UserModel>> registerListener = new Listener<RequestResult<UserModel>>() {
		@Override
		public void onResponse(RequestResult<UserModel> arg0) {
			dismissLoadingDialog();
			if (arg0.flag == 1) {
				LoginUtils loginUtils = new LoginUtils(RegisterActivity.this);
				loginUtils.login(phone, pwd);
				aty.finish();
			}
			showToastMsg(arg0.msg);
		}
	};
	
	private void setVerfyEt(boolean isShow) {
		if (isShow) {
			etVerfy.setEnabled(true);
		} else {
			etVerfy.setEnabled(false);
		}
	}

}
